/**
 * 
 */
package com.demo2do.edoos.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Component;

import com.demo2do.edoos.entity.User;

/**
 * @author Downpour
 */
@Component("userDaoSupport")
public class UserDaoSupport {
	
	private DataSource dataSource;
	
	private NamedParameterJdbcTemplate jdbcTemplate;
	
	/**
	 * @param dataSource the dataSource to set
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplate = new NamedParameterJdbcTemplate(this.dataSource);
	}

	/**
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	public boolean login(String name, String password) {
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("name", name);
		
		List<Map<String, Object>> users = jdbcTemplate.queryForList("SELECT * FROM USER user WHERE user.name = :name", parameters);
		
		if(users.isEmpty()) {
			return false;
		} else {
			
			Map<String, Object> user = users.get(0);
			
			String passwordFromDB = (String) user.get("password");
			
			if(password.equals(passwordFromDB)) {
				return true;
			}
			
		}
		
		return false;
	}

	/**
	 * 
	 * @param name
	 * @return
	 */
	public List<User> getUserByName(String name) {
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("name", name);
		
		return jdbcTemplate.query("SELECT * FROM USER user WHERE user.name = :name", parameters, ParameterizedBeanPropertyRowMapper.newInstance(User.class));
	}
	
	/**
	 * 
	 * @param user
	 */
	public void create(User user) {
		jdbcTemplate.update("INSERT INTO USER (`name`, `password`, `create_date`) VALUES (:name, :password, :createDate)", new BeanPropertySqlParameterSource(user));
	}
}
